/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util;

/**
 * 整型序列值，默认从1从0x7FFFFFFF(最大值)<br><br>
 * 设置min必须>=1，否则默认为1<br>
 * 设置max必须<=0x7FFFFFFF，否则默认为0x7FFFFFFF
 * @Title com.enfry.util.IntSequence
 * @author Penghu
 * @date 2016年11月10日
 */
public class IntSequence
{
    protected int min = 1;
    protected int max = 0x7FFFFFFF;
    
    protected int sequence = 1;
    protected Object lock = new Object();
    
    public IntSequence()
    {
    }
    
    public IntSequence(int min)
    {
        if (min <= 0)
            min = 1;
        this.min = min;
        this.sequence = min;
    }
    
    public IntSequence(int min, int max)
    {
        if (min <= 0)
            min = 1;
        
        if (max <= min)
            throw new RuntimeException("创建Sequence失败，最大值不得小于等于最小值");

        this.min = min;
        this.max = max;
        this.sequence = min;
    }
    
    public int getMin()
    {
        return min;
    }
    
    public int getMax()
    {
        return max;
    }
    
    public int current()
    {
        return sequence;
    }
    
    public int next()
    {
        synchronized (lock)
        {
            if (sequence <= min || sequence > max)
                sequence = min;//0x7FFFFFFF+1=负数<0，取sequence<=min，其他取sequence>max
            
            return sequence++;
        }
    }
}
